/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojo.Category;
import pojo.Extraprice;
import java.util.ArrayList;
import java.util.Collection;
import pojo.Food;

/**
 *
 * @author A7med Kotb
 */
public class CategoryJpaController implements Serializable {

    public CategoryJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Category category) throws RollbackFailureException, Exception {
        if (category.getExtrapriceCollection() == null) {
            category.setExtrapriceCollection(new ArrayList<Extraprice>());
        }
        if (category.getFoodCollection() == null) {
            category.setFoodCollection(new ArrayList<Food>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Category categoryRel = category.getCategory();
            if (categoryRel != null) {
                categoryRel = em.getReference(categoryRel.getClass(), categoryRel.getId());
                category.setCategory(categoryRel);
            }
            Category categoryId = category.getCategoryId();
            if (categoryId != null) {
                categoryId = em.getReference(categoryId.getClass(), categoryId.getId());
                category.setCategoryId(categoryId);
            }
            Collection<Extraprice> attachedExtrapriceCollection = new ArrayList<Extraprice>();
            for (Extraprice extrapriceCollectionExtrapriceToAttach : category.getExtrapriceCollection()) {
                extrapriceCollectionExtrapriceToAttach = em.getReference(extrapriceCollectionExtrapriceToAttach.getClass(), extrapriceCollectionExtrapriceToAttach.getId());
                attachedExtrapriceCollection.add(extrapriceCollectionExtrapriceToAttach);
            }
            category.setExtrapriceCollection(attachedExtrapriceCollection);
            Collection<Food> attachedFoodCollection = new ArrayList<Food>();
            for (Food foodCollectionFoodToAttach : category.getFoodCollection()) {
                foodCollectionFoodToAttach = em.getReference(foodCollectionFoodToAttach.getClass(), foodCollectionFoodToAttach.getId());
                attachedFoodCollection.add(foodCollectionFoodToAttach);
            }
            category.setFoodCollection(attachedFoodCollection);
            em.persist(category);
            if (categoryRel != null) {
                Category oldCategoryIdOfCategoryRel = categoryRel.getCategoryId();
                if (oldCategoryIdOfCategoryRel != null) {
                    oldCategoryIdOfCategoryRel.setCategory(null);
                    oldCategoryIdOfCategoryRel = em.merge(oldCategoryIdOfCategoryRel);
                }
                categoryRel.setCategoryId(category);
                categoryRel = em.merge(categoryRel);
            }
            if (categoryId != null) {
                Category oldCategoryOfCategoryId = categoryId.getCategory();
                if (oldCategoryOfCategoryId != null) {
                    oldCategoryOfCategoryId.setCategoryId(null);
                    oldCategoryOfCategoryId = em.merge(oldCategoryOfCategoryId);
                }
                categoryId.setCategory(category);
                categoryId = em.merge(categoryId);
            }
            for (Extraprice extrapriceCollectionExtraprice : category.getExtrapriceCollection()) {
                Category oldCategoryIdOfExtrapriceCollectionExtraprice = extrapriceCollectionExtraprice.getCategoryId();
                extrapriceCollectionExtraprice.setCategoryId(category);
                extrapriceCollectionExtraprice = em.merge(extrapriceCollectionExtraprice);
                if (oldCategoryIdOfExtrapriceCollectionExtraprice != null) {
                    oldCategoryIdOfExtrapriceCollectionExtraprice.getExtrapriceCollection().remove(extrapriceCollectionExtraprice);
                    oldCategoryIdOfExtrapriceCollectionExtraprice = em.merge(oldCategoryIdOfExtrapriceCollectionExtraprice);
                }
            }
            for (Food foodCollectionFood : category.getFoodCollection()) {
                Category oldCategoryIdOfFoodCollectionFood = foodCollectionFood.getCategoryId();
                foodCollectionFood.setCategoryId(category);
                foodCollectionFood = em.merge(foodCollectionFood);
                if (oldCategoryIdOfFoodCollectionFood != null) {
                    oldCategoryIdOfFoodCollectionFood.getFoodCollection().remove(foodCollectionFood);
                    oldCategoryIdOfFoodCollectionFood = em.merge(oldCategoryIdOfFoodCollectionFood);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Category category) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Category persistentCategory = em.find(Category.class, category.getId());
            Category categoryRelOld = persistentCategory.getCategory();
            Category categoryRelNew = category.getCategory();
            Category categoryIdOld = persistentCategory.getCategoryId();
            Category categoryIdNew = category.getCategoryId();
            Collection<Extraprice> extrapriceCollectionOld = persistentCategory.getExtrapriceCollection();
            Collection<Extraprice> extrapriceCollectionNew = category.getExtrapriceCollection();
            Collection<Food> foodCollectionOld = persistentCategory.getFoodCollection();
            Collection<Food> foodCollectionNew = category.getFoodCollection();
            List<String> illegalOrphanMessages = null;
            for (Extraprice extrapriceCollectionOldExtraprice : extrapriceCollectionOld) {
                if (!extrapriceCollectionNew.contains(extrapriceCollectionOldExtraprice)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Extraprice " + extrapriceCollectionOldExtraprice + " since its categoryId field is not nullable.");
                }
            }
            for (Food foodCollectionOldFood : foodCollectionOld) {
                if (!foodCollectionNew.contains(foodCollectionOldFood)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Food " + foodCollectionOldFood + " since its categoryId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (categoryRelNew != null) {
                categoryRelNew = em.getReference(categoryRelNew.getClass(), categoryRelNew.getId());
                category.setCategory(categoryRelNew);
            }
            if (categoryIdNew != null) {
                categoryIdNew = em.getReference(categoryIdNew.getClass(), categoryIdNew.getId());
                category.setCategoryId(categoryIdNew);
            }
            Collection<Extraprice> attachedExtrapriceCollectionNew = new ArrayList<Extraprice>();
            for (Extraprice extrapriceCollectionNewExtrapriceToAttach : extrapriceCollectionNew) {
                extrapriceCollectionNewExtrapriceToAttach = em.getReference(extrapriceCollectionNewExtrapriceToAttach.getClass(), extrapriceCollectionNewExtrapriceToAttach.getId());
                attachedExtrapriceCollectionNew.add(extrapriceCollectionNewExtrapriceToAttach);
            }
            extrapriceCollectionNew = attachedExtrapriceCollectionNew;
            category.setExtrapriceCollection(extrapriceCollectionNew);
            Collection<Food> attachedFoodCollectionNew = new ArrayList<Food>();
            for (Food foodCollectionNewFoodToAttach : foodCollectionNew) {
                foodCollectionNewFoodToAttach = em.getReference(foodCollectionNewFoodToAttach.getClass(), foodCollectionNewFoodToAttach.getId());
                attachedFoodCollectionNew.add(foodCollectionNewFoodToAttach);
            }
            foodCollectionNew = attachedFoodCollectionNew;
            category.setFoodCollection(foodCollectionNew);
            category = em.merge(category);
            if (categoryRelOld != null && !categoryRelOld.equals(categoryRelNew)) {
                categoryRelOld.setCategoryId(null);
                categoryRelOld = em.merge(categoryRelOld);
            }
            if (categoryRelNew != null && !categoryRelNew.equals(categoryRelOld)) {
                Category oldCategoryIdOfCategoryRel = categoryRelNew.getCategoryId();
                if (oldCategoryIdOfCategoryRel != null) {
                    oldCategoryIdOfCategoryRel.setCategory(null);
                    oldCategoryIdOfCategoryRel = em.merge(oldCategoryIdOfCategoryRel);
                }
                categoryRelNew.setCategoryId(category);
                categoryRelNew = em.merge(categoryRelNew);
            }
            if (categoryIdOld != null && !categoryIdOld.equals(categoryIdNew)) {
                categoryIdOld.setCategory(null);
                categoryIdOld = em.merge(categoryIdOld);
            }
            if (categoryIdNew != null && !categoryIdNew.equals(categoryIdOld)) {
                Category oldCategoryOfCategoryId = categoryIdNew.getCategory();
                if (oldCategoryOfCategoryId != null) {
                    oldCategoryOfCategoryId.setCategoryId(null);
                    oldCategoryOfCategoryId = em.merge(oldCategoryOfCategoryId);
                }
                categoryIdNew.setCategory(category);
                categoryIdNew = em.merge(categoryIdNew);
            }
            for (Extraprice extrapriceCollectionNewExtraprice : extrapriceCollectionNew) {
                if (!extrapriceCollectionOld.contains(extrapriceCollectionNewExtraprice)) {
                    Category oldCategoryIdOfExtrapriceCollectionNewExtraprice = extrapriceCollectionNewExtraprice.getCategoryId();
                    extrapriceCollectionNewExtraprice.setCategoryId(category);
                    extrapriceCollectionNewExtraprice = em.merge(extrapriceCollectionNewExtraprice);
                    if (oldCategoryIdOfExtrapriceCollectionNewExtraprice != null && !oldCategoryIdOfExtrapriceCollectionNewExtraprice.equals(category)) {
                        oldCategoryIdOfExtrapriceCollectionNewExtraprice.getExtrapriceCollection().remove(extrapriceCollectionNewExtraprice);
                        oldCategoryIdOfExtrapriceCollectionNewExtraprice = em.merge(oldCategoryIdOfExtrapriceCollectionNewExtraprice);
                    }
                }
            }
            for (Food foodCollectionNewFood : foodCollectionNew) {
                if (!foodCollectionOld.contains(foodCollectionNewFood)) {
                    Category oldCategoryIdOfFoodCollectionNewFood = foodCollectionNewFood.getCategoryId();
                    foodCollectionNewFood.setCategoryId(category);
                    foodCollectionNewFood = em.merge(foodCollectionNewFood);
                    if (oldCategoryIdOfFoodCollectionNewFood != null && !oldCategoryIdOfFoodCollectionNewFood.equals(category)) {
                        oldCategoryIdOfFoodCollectionNewFood.getFoodCollection().remove(foodCollectionNewFood);
                        oldCategoryIdOfFoodCollectionNewFood = em.merge(oldCategoryIdOfFoodCollectionNewFood);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = category.getId();
                if (findCategory(id) == null) {
                    throw new NonexistentEntityException("The category with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Category category;
            try {
                category = em.getReference(Category.class, id);
                category.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The category with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Extraprice> extrapriceCollectionOrphanCheck = category.getExtrapriceCollection();
            for (Extraprice extrapriceCollectionOrphanCheckExtraprice : extrapriceCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Category (" + category + ") cannot be destroyed since the Extraprice " + extrapriceCollectionOrphanCheckExtraprice + " in its extrapriceCollection field has a non-nullable categoryId field.");
            }
            Collection<Food> foodCollectionOrphanCheck = category.getFoodCollection();
            for (Food foodCollectionOrphanCheckFood : foodCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Category (" + category + ") cannot be destroyed since the Food " + foodCollectionOrphanCheckFood + " in its foodCollection field has a non-nullable categoryId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Category categoryRel = category.getCategory();
            if (categoryRel != null) {
                categoryRel.setCategoryId(null);
                categoryRel = em.merge(categoryRel);
            }
            Category categoryId = category.getCategoryId();
            if (categoryId != null) {
                categoryId.setCategory(null);
                categoryId = em.merge(categoryId);
            }
            em.remove(category);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Category> findCategoryEntities() {
        return findCategoryEntities(true, -1, -1);
    }

    public List<Category> findCategoryEntities(int maxResults, int firstResult) {
        return findCategoryEntities(false, maxResults, firstResult);
    }

    private List<Category> findCategoryEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Category.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Category findCategory(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Category.class, id);
        } finally {
            em.close();
        }
    }

    public int getCategoryCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Category> rt = cq.from(Category.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
